package igeomap.foundation;

import igeomap.controller.ControllerScattaFoto;
import igeomap.domain.Fotocamera;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.content.Intent;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;

public class CreateFotoHolder implements PictureCallback {
	private static final String VIEW_LOG_TAG = "VIEW_LOG_TAG";
	private static CreateFotoHolder createFotoHolder = null;
	private File mediaFile;
	
	public static CreateFotoHolder getCreateFotoHolderIstance()
	{
		if(createFotoHolder==null)
		{
			createFotoHolder=new CreateFotoHolder();
		
		}
		return createFotoHolder;
	}
	
	@Override
	public void onPictureTaken(byte[] arg0, Camera arg1) 
	{
		// TODO Auto-generated method stub
		

	        getOutputMediaFile();
	        if (mediaFile == null){
	            Log.d(VIEW_LOG_TAG, "Error creating media file, check storage permissions: ");
	            return;
	        }

	        try {
	            FileOutputStream fos = new FileOutputStream(mediaFile);
	            fos.write(arg0);
	            fos.close();
	        } catch (FileNotFoundException e) {
	            Log.d(VIEW_LOG_TAG, "File not found: " + e.getMessage());
	        } catch (IOException e) {
	            Log.d(VIEW_LOG_TAG, "Error accessing file: " + e.getMessage());
	        }
	        try{
	        	  Thread.currentThread();
			   	  Thread.sleep(2000);
	        	  Fotocamera f=Fotocamera.getFotocameraIstance();
	        	  f.StartPreview();
	        	}
	        	catch(InterruptedException ie){
	        	
	        	}
	}
	
	public void getOutputMediaFile(){
	    // To be safe, you should check that the SDCard is mounted
	    // using Environment.getExternalStorageState() before doing this.

	    File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "MyCameraApp");
	    // This location works best if you want the created images to be shared
	    // between applications and persist after your app has been uninstalled.

	    // Create the storage directory if it does not exist
	    if (! mediaStorageDir.exists()){
	        if (! mediaStorageDir.mkdirs()){
	            Log.d("MyCameraApp", "failed to create directory");
	            
	        }
	    }
	    // Create a media file name
	    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
	    
	    mediaFile = new File(mediaStorageDir.getPath() + File.separator +"IMG_"+ timeStamp + ".jpg");
	   // Log.d("MyCameraApp", mediaFile.getAbsolutePath());
	}
	
	public File getFile()
	{
		 
		return mediaFile;
		
	}

}
